
import { getProductsDetail, updateProducts } from '@/api/farmer/products';

export const useProductStore = defineStore('product', {
    state: () => ({
        // 商品基本信息
        productInfo: {
            id: '',
            productsName: '',
            mainImage: '',
            status: '1',
            description: '',
            categoryId: '',
            storageCondition: '',
            shelfLife: 0,
            origin: [],
            images: []
        },
        // 规格列表
        specifications: [],
        // SKU列表
        skus: [],
        // 是否已加载数据
        isLoaded: false
    }),

    getters: {
        // 获取商品完整数据
        productData: (state) => ({
            ...state.productInfo,
            specifications: state.specifications,
            skus: state.skus
        })
    },

    actions: {
        // 加载商品详情
        async loadProductDetail(productId) {
            try {
                // 如果已经加载过且ID相同，则不重复加载
                if (this.isLoaded && this.productInfo.id === productId) {
                    return;
                }

                const response = await getProductsDetail(productId);
                if (response.code === 200) {
                    const { data } = response;
                    
                    // 更新商品基本信息
                    this.productInfo = {
                        id: data.id,
                        productsName: data.productsName,
                        mainImage: data.mainImage,
                        status: data.status,
                        description: data.description,
                        categoryId: data.categoryId,
                        storageCondition: data.storageCondition,
                        shelfLife: data.shelfLife,
                        origin: data.origin,
                        images: data.images || []
                    };

                    // 更新规格信息，修正数据结构
                    this.specifications = data.specifications.map(spec => ({
                        id: spec.id,
                        name: spec.name,
                        values: spec.values.map((value, index) => ({
                            id: value.id || `${spec.id}_${index}`,
                            value: value.value || value, // 处理直接是字符串的情况
                            sort: value.sort || index
                        }))
                    }));

                    // 更新SKU信息
                    this.skus = data.skus;
                    this.isLoaded = true;
                }
            } catch (error) {
                console.error('加载商品详情失败:', error);
                throw error;
            }
        },

        // 更新商品基本信息
        updateProductInfo(data) {
            this.productInfo = { ...this.productInfo, ...data };
        },

        // 更新规格
        async updateSpecifications(specifications) {
            try {
                // 转换规格数据格式
                const formattedSpecs = specifications.map(spec => ({
                    id: spec.id,
                    name: spec.name,
                    values: spec.values.map(v => v.value)
                }));

                // 构建完整的更新数据
                const updateData = {
                    ...this.productInfo,
                    specifications: formattedSpecs,
                    skus: this.skus
                };

                const response = await updateProducts(this.productInfo.id, updateData);
                if (response.code === 200) {
                    this.specifications = specifications;
                    return true;
                }
                return false;
            } catch (error) {
                console.error('更新规格失败:', error);
                throw error;
            }
        },

        // 更新SKU
        async updateSkus(skus) {
            try {
                // 构建完整的更新数据
                const updateData = {
                    ...this.productInfo,
                    specifications: this.specifications.map(spec => ({
                        id: spec.id,
                        name: spec.name,
                        values: spec.values.map(v => v.value)
                    })),
                    skus: skus
                };

                const response = await updateProducts(this.productInfo.id, updateData);
                if (response.code === 200) {
                    this.skus = skus;
                    return true;
                }
                return false;
            } catch (error) {
                console.error('更新SKU失败:', error);
                throw error;
            }
        },

        // 保存所有更改
        async saveAll() {
            try {
                const updateData = {
                    ...this.productInfo,
                    specifications: this.specifications.map(spec => ({
                        id: spec.id,
                        name: spec.name,
                        values: spec.values.map(v => v.value)
                    })),
                    skus: this.skus
                };

                const response = await updateProducts(this.productInfo.id, updateData);
                return response.code === 200;
            } catch (error) {
                console.error('保存失败:', error);
                throw error;
            }
        },

        // 重置状态
        resetState() {
            this.productInfo = {
                id: '',
                productsName: '',
                mainImage: '',
                status: '1',
                description: '',
                categoryId: '',
                storageCondition: '',
                shelfLife: 0,
                origin: [],
                images: []
            };
            this.specifications = [];
            this.skus = [];
            this.isLoaded = false;
        }
    }
}); 